package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 * @author GRS
 * @since 2024/4/24 下午10:08
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    @Value("${save-path}")
    private String SAVE_PATH;

    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file) throws IOException
    {
        String uuid = (UUID.randomUUID() + "").replaceAll("-", "");
        file.transferTo(new File(SAVE_PATH + "/" + uuid + ".png"));
        return R.success(uuid + ".png");
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException
    {
        // 通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(SAVE_PATH + "/" + name);

        // 通过输出流将文件写回浏览器，在浏览器展示图片
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/png");

        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fileInputStream.read(bytes)) != -1)
        {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }

        // 关闭资源
        outputStream.close();
        fileInputStream.close();
    }
}